package com.hzz.service.examine;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hzz.api.examine.IExamineEvaluateService;
import com.hzz.api.examine.IExamineResultDetailService;
import com.hzz.api.examine.IExamineResultService;
import com.hzz.api.examine.IExamineTargetDetailService;
import com.hzz.api.examine.IExamineTargetService;
import com.hzz.dao.examine.IExamineEvaluateDao;
import com.hzz.dto.examine.ExamineEvaluateDto;
import com.hzz.dto.examine.ExamineResultDetailDto;
import com.hzz.dto.examine.ExamineResultDto;
import com.hzz.dto.examine.ExamineTargetDetailDto;
import com.hzz.dto.examine.ExamineTargetDto;
import com.hzz.entity.examine.ExamineEvaluate;
import com.hzz.framework.Response;
import com.hzz.framework.SysErrorCode;
import com.hzz.framework.annotation.FeignService;
import com.hzz.framework.exception.ServiceException;
import com.hzz.framework.service.BaseService;
import com.hzz.framework.util.CommonConstant;
import com.hzz.framework.util.IdUtil;

import lombok.extern.slf4j.Slf4j;

@FeignService
@Slf4j
public class ExamineEvaluateService extends BaseService implements IExamineEvaluateService {
	@Autowired
	IExamineEvaluateDao examineEvaluateDao;
	@Autowired
	IExamineResultService examineResultService;
	@Autowired
	IExamineResultDetailService examineResultDetailService;
	@Autowired
	IExamineTargetService examineTargetService;
	@Autowired
	IExamineTargetDetailService examineTargetDetailService;

	@Override
	@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = CommonConstant.DB_DEFAULT_TIMEOUT, rollbackFor = {
			Exception.class, RuntimeException.class })
	public Response saveOrUpdateData(ExamineEvaluateDto dto) throws Exception {
		Response result = new Response(0, "success");
		try {
			ExamineEvaluate entity = copyTo(dto, ExamineEvaluate.class);
			// 判断数据是否存在
			if (examineEvaluateDao.isDataExist(entity) != 0) {
				// 数据存在
				examineEvaluateDao.update(entity);

				syncResult(dto, 2);
			} else {
				// 新增
				if (entity.getId() == null) {
					entity.setId(IdUtil.nextId());
				}
				examineEvaluateDao.insert(entity);
				result.data = entity.getId();

				dto.setId(entity.getId());
				syncResult(dto, 1);
			}
		} catch (Exception e) {
			log.error("信息保存异常!", e);
			throw new ServiceException(SysErrorCode.defaultError, e.getMessage());
		}
		return result;
	}

	@Override
	public String deleteData(ExamineEvaluateDto dto) throws Exception {
		String result = "success";
		try {
			ExamineEvaluate entity = copyTo(dto, ExamineEvaluate.class);
			if (examineEvaluateDao.deleteByPrimaryKey(entity) == 0) {
				throw new RuntimeException("数据不存在!");
			}
		} catch (Exception e) {
			log.error("物理删除异常!", e);
			throw new ServiceException(SysErrorCode.defaultError, e.getMessage());
		}
		return result;
	}

	@Override
	@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = CommonConstant.DB_DEFAULT_TIMEOUT, rollbackFor = {
			Exception.class, RuntimeException.class })
	public String deleteDataById(ExamineEvaluateDto dto) throws Exception {
		String result = "success";
		try {
			ExamineEvaluate entity = copyTo(dto, ExamineEvaluate.class);
			if (examineEvaluateDao.deleteById(entity) == 0) {
				throw new RuntimeException("数据不存在!");
			}
			syncResult(dto, 0);
		} catch (Exception e) {
			log.error("逻辑删除异常!", e);
			throw new ServiceException(SysErrorCode.defaultError, e.getMessage());
		}
		return result;
	}

	@Override
	public PageInfo findDataIsPage(ExamineEvaluateDto dto) throws Exception {
		PageInfo pageInfo = null;
		try {
			ExamineEvaluate entity = copyTo(dto, ExamineEvaluate.class);
			PageHelper.startPage(PN(dto.getPageNum()), PS(dto.getPageSize()));
			List list = examineEvaluateDao.findDataIsPage(entity);
			pageInfo = new PageInfo(list);
			pageInfo.setList(copyTo(pageInfo.getList(), ExamineEvaluateDto.class));
		} catch (Exception e) {
			log.error("信息[分页]查询异常!", e);
			throw new ServiceException(SysErrorCode.defaultError, e.getMessage());
		}
		return pageInfo;
	}

	@Override
	public List<ExamineEvaluateDto> findDataIsList(ExamineEvaluateDto dto) throws Exception {
		List<ExamineEvaluateDto> results = null;
		try {
			ExamineEvaluate entity = copyTo(dto, ExamineEvaluate.class);
			results = copyTo(examineEvaluateDao.findDataIsList(entity), ExamineEvaluateDto.class);
		} catch (Exception e) {
			log.error("信息[列表]查询异常!", e);
			throw new ServiceException(SysErrorCode.defaultError, e.getMessage());
		}
		return results;
	}

	@Override
	public ExamineEvaluateDto findDataById(ExamineEvaluateDto dto) throws Exception {
		ExamineEvaluateDto result = null;
		try {
			ExamineEvaluate entity = copyTo(dto, ExamineEvaluate.class);
			result = copyTo(examineEvaluateDao.selectByPrimaryKey(entity), ExamineEvaluateDto.class);
		} catch (Exception e) {
			log.error("信息[详情]查询异常!", e);
			throw new ServiceException(SysErrorCode.defaultError, e.getMessage());
		}
		return result;
	}

	/**
	 * 同步该评估对应的考核结果
	 * 
	 * @param dto
	 * @param flag
	 *            0删除、1新增、2修改
	 */
	private void syncResult(ExamineEvaluateDto dto, int flag) throws Exception {
		// 新增考核结果
		if (flag == 1) {
			addResult(dto);
			return;
		}

		// 查出所有和该评估有关联的结果数据
		ExamineResultDto param = new ExamineResultDto();
		param.setEvaluateId(dto.getId());
		List<ExamineResultDto> list = examineResultService.findDataIsList(param);
		// 删除考核结果
		if (flag == 0) {
			delResult(list);
			return;
		}

		// 修改考核结果
		if (flag == 2) {
			if (list == null || list.isEmpty()) {
				// 新增考核结果
				addResult(dto);
			} else {
				ExamineResultDto old = list.get(0);
				if (old.getTargetId().longValue() == dto.getTargetId().longValue()) {
					// return;// 不改变考核结果
				}
				// 先删除，再添加
				delResult(list);
				addResult(dto);
			}
		}
	}

	/**
	 * 添加考核结果
	 * 
	 * @param dto
	 * @throws Exception
	 */
	private void addResult(ExamineEvaluateDto dto) throws Exception {
		// 查询考核目标
		ExamineTargetDto target = new ExamineTargetDto();
		target.setId(dto.getTargetId());
		target = examineTargetService.findDataById(target);
		// 查询考核目标明细
		ExamineTargetDetailDto detail = new ExamineTargetDetailDto();
		detail.setTargetId(dto.getTargetId());
		List<ExamineTargetDetailDto> details = examineTargetDetailService.findDataIsList(detail);
		// 设置考核结果
		List<ExamineResultDetailDto> resultDetails = new ArrayList<>();// 考核结果自评分明细
		ExamineResultDto result = new ExamineResultDto();
		result.setCreateId(dto.getCreateId());
		result.setEvaluateId(dto.getId());
		result.setTargetId(dto.getTargetId());
		result.setLeaderScore(new BigDecimal("0"));// 领导评分
		BigDecimal autoScore = new BigDecimal("0");// 自动评分
		BigDecimal selfScore = new BigDecimal("0");// 自评分
		for (ExamineTargetDetailDto temp : details) {
			ExamineResultDetailDto resultDetail = new ExamineResultDetailDto();
			if (temp.getScoreType().intValue() == 1) {// 自动评分
				result.setAutoScore(temp.getNormScore());// 自动评分默认为标准分
				autoScore = autoScore.add(temp.getNormScore());
				// selfScore = selfScore
				// .add(temp.getNormScore().multiply(target.getAutoScale()).divide(new
				// BigDecimal(100)));
				resultDetail.setScore(temp.getNormScore());
			} else {
				resultDetail.setScore(new BigDecimal("0"));// 人工评分默认为0
			}

			resultDetail.setCreateId(dto.getCreateId());
			resultDetail.setEvaluateId(dto.getId());
			resultDetail.setTargetId(dto.getTargetId());
			resultDetail.setTargetDetailId(temp.getId());
			resultDetails.add(resultDetail);
		}
		// 全部初始化为自动评分得分
		autoScore = target.getAutoScale();// (各项自评分/各项标准分*100*权重)相当于直接取比例值作分数
		result.setTotalScore(autoScore);
		result.setAutoScore(autoScore);
		result.setSelfScore(autoScore);
		String[] userIds = dto.getSubordinateIds().split(",");
		String[] userNames = dto.getSubordinateNames().split(",");
		for (int i = 0; i < userIds.length; i++) {
			String userId = userIds[i];
			String userName = userNames[i];
			if (StringUtils.isBlank(userId)) {
				continue;
			}
			result.setId(null); // 清空ID，避免因上次的ID没清掉导致更新数据
			result.setUserId(Long.valueOf(userId));
			result.setUserName(userName);
			// 保存评分结果
			Response res = examineResultService.saveOrUpdateData(result);
			if (res.getCode() == 0 && res.getData() != null) {
				// 保存评分明细
				for (ExamineResultDetailDto resultDetail : resultDetails) {
					resultDetail.setId(null); // 清空ID，避免因上次的ID没清掉导致更新数据
					resultDetail.setUserId(Long.valueOf(userId));
					resultDetail.setUserName(userName);
					resultDetail.setResultId((Long) res.getData());
					examineResultDetailService.saveOrUpdateData(resultDetail);
				}
			}
		}
	}

	/**
	 * 删除考核结果
	 * 
	 * @param list
	 * @throws Exception
	 */
	private void delResult(List<ExamineResultDto> list) throws Exception {
		if (list == null) {
			return;
		}
		for (ExamineResultDto obj : list) {
			obj.setDelFlag(1);
			examineResultService.deleteDataById(obj);
		}
	}

}
